<script>

if(!String.prototype.startsWith){
    String.prototype.startsWith = function (str) {
        return !this.indexOf(str);
    }
}

if(!String.prototype.contains) {
	String.prototype.contains = function(it) { 
		return this.indexOf(it) != -1;
	};
}

// This array is used to detect circular http to https redirects
var urlHistoryMap = [];

// Initialize stored values
init();

chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
	
	if(info.status == "loading") {
		
		var isDisabled = localStorage.getItem('is-disabled');
		
		/*
		 * The enablePageAction variable indicates if we show the 
		 * Use HTTPS icon in the address bar via a page action
		 */
		var enablePageAction = localStorage.getItem('enable-page-action');
		
		if("false" == isDisabled && tab.url.startsWith("http://")) {
			
			// Getting a list of sites from localStorage
			var sites = JSON.parse(localStorage.getItem('sites'));
			
			for(var i in sites) {
				
				if(tab.url.contains(sites[i])) {
					
					// Detecting if there is a circular http to https request
					var previousUrl = urlHistoryMap[tabId];
					if(null == previousUrl || previousUrl != tab.url) {
						
						chrome.tabs.update(tab.id, {url: tab.url.replace("http://", "https://"), selected: true});
						urlHistoryMap[tabId] = tab.url;
					}
					else {
						console.log("Detected circular redirect http --> https --> http --> https --> etc.")
					}
				}
				else {
					chrome.pageAction.hide(tabId);
				}
			}
		}
		else if("true" == enablePageAction && "false" == isDisabled && tab.url.startsWith("https://")) {
			
			var sites = JSON.parse(localStorage.getItem('sites'));
			
			for(var i in sites) {
				
				if(tab.url.contains(sites[i])) {
					
					chrome.pageAction.show(tabId);
				}
			}
		}
		else {
			
			chrome.pageAction.hide(tabId);
		}
	}
});


function init() {
	
	// Check if we have stored sites
	var storedSites = localStorage.getItem('sites');

	// IF sites is null, we initialzie it 
	if(null == storedSites) {
		
		var defaultSites = ["facebook.com", "twitter.com"];
		localStorage['sites'] = JSON.stringify(defaultSites); 
	}
	
	// Initialize sites enabled flag
	var isDisabled = localStorage.getItem('is-disabled');
	
	if(null == isDisabled) {
		
		localStorage['sites-enabled'] = "false";
	}
	
	// Initizlize enable page action
	var enablePageAction = localStorage.getItem('enable-page-action');
	
	if(null == enablePageAction) {
		
		localStorage['enable-page-action'] = "false";
	}
}

</script>